<template>
    <div class="api">
        <h2>API</h2>
        <input placeholder="请输入关键字" v-model.lazy="keyword" />
        <ul>
            <li v-for="d in list" :key="d.id" @click="play(d)">
                <img :src="d.cover" alt="" />
                <div class="info">
                    <h4>{{d.song}}</h4>
                    <p>{{d.singer}}</p>
                </div>
            </li>
        </ul>
        <!-- <audio ref="audio" :src="list[song]||{}.url" /> -->
        <!-- this.$refs.audio -->
        <!-- <player :playing="playing" :playlist="list" :current-index="song" @set-playing="playing=$event" @set-current-index="song=$event" /> -->

    </div>
</template>

<script>
//不加路径 导入包/库
// import axios from 'axios';
    export default {
        data(){
            return {
                // playing:false,
                // song:-1,//播放歌曲下标
                list:[],
                keyword:''
            }
        },
        watch:{
            keyword(){
                //POST请求,第一个参数是API路径,第二个参数POST的参数,(这里用JSON数据格式)
                this.request.post('/song-search',{
                    keyword:this.keyword
                }).then(({data})=>{
                    console.log(data);
                })
            }
        },
        methods:{
            play(song){
                // this.song=i;
                // this.playing=true;
                //先把playlist取出来,数据需要深拷贝
                // const playlist = this.$store.state.playlist.slice()
                //深拷贝
                const playlist = JSON.parse(JSON.stringify(this.$store.state.playlist))
                const index = playlist.findIndex(i=>i.id===song.id);
                if(index>-1){
                    playlist.splice(index,1)
                }
                playlist.unshift(song);
                this.$store.commit('setPlaying',true)
                this.$store.commit('setPlaylist',playlist)
                this.$store.commit('setCurrentIndex',0)

                // setTimeout(()=>{
                //     document.querySelector('audio').play()
                // },1000)

            }
        },
        created(){
            this.request.get('/hit-single-list').then(({data})=>{
                this.list=data.data
                console.log(data);
            })

            // const xhr = new XMLHttpRequest();
            // xhr.onreadystatechange=()=>{
            //     if(xhr.readyState===4&&xhr.status===200){
            //         console.log(JSON.parse(xhr.responseText));
            //     }
            // }
            // xhr.open('GET','/api/hit-single-list');
            // xhr.send(null)

        }
    }
</script>

<style lang="sass" scoped>
.api
    li
        display: flex
        justify-content: start
        margin-top: 20px
    img
        border-radius: 20%
        width: 50px
        height: 50px
        margin-right: 50px
</style>
